package com.wx.network.client;

import com.wx.cache.ChannelCache;
import com.wx.network.codec.RpcClientDecoder;
import com.wx.network.codec.RpcClientEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class RpcClientSocket {
   private   Bootstrap bootstrap;

    public Bootstrap getBootstrap(){
       if(bootstrap==null){
           NioEventLoopGroup executors = new NioEventLoopGroup();

           Bootstrap bootstrap = new Bootstrap();
           bootstrap.group(executors);
           bootstrap.channel(NioSocketChannel.class)
                   .handler(new ChannelInitializer<SocketChannel>() {
                       @Override
                       protected void initChannel(SocketChannel socketChannel) throws Exception {
                           //添加编码器与解码器
                           socketChannel.pipeline().addLast("encoder",new RpcClientEncoder());
                           socketChannel.pipeline().addLast("decoder",new RpcClientDecoder());
                       //    socketChannel.pipeline().addLast(new IdleStateHandler(5,5,5, TimeUnit.SECONDS));
                           socketChannel.pipeline().addLast(new RpcClientHandler());
                       }
                   });
           this.bootstrap=bootstrap;
           return bootstrap;
       }else {
           return  bootstrap;
       }
    }

    public void connect(String ip, int port,String serverName) throws InterruptedException {
        Bootstrap bootstrap = getBootstrap();
        ChannelFuture future = bootstrap.connect(ip, port).sync();
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if(future.isSuccess()){
                    log.info("客户端连接服务器成功");
                    ChannelCache.putChannel(serverName,channelFuture.channel());
                    log.info("添加连接信息到缓存{}：{}",serverName,channelFuture.channel().id());
                }
                if(!future.isSuccess()){
                    Thread.currentThread().sleep(2000);
                    log.info("客户重新连接服务器");
                    connect(ip,port,serverName);
                }
            }
        });
        ChannelFuture sync = future.channel().closeFuture().sync();
        sync.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if(sync.isSuccess()){

                }
            }
        });

    }
}
